const { request } = require('../../utils/request');
const pageBehavior = require('../../utils/pageBehavior');
const { formatDate } = require('../../utils/common');

Page({
  behaviors: [pageBehavior],

  data: {
    tokenPresent: false,
    greeting: '欢迎',
    healthStatus: {
      statusClass: '',
      message: '点击下方按钮进行系统自检',
      checkedAt: '',
      loading: false
    },
    pageLoading: false,
    featureError: '',
    features: [
      {
        id: 1,
        title: '资料填写',
        subtitle: '完成个人信息录入',
        status: 'info',
        tag: '必填',
        tagType: 'warning',
        caption: '完成后提交审核',
        path: '/pages/profile/profile'
      },
      {
        id: 2,
        title: '入学测验',
        subtitle: '完成新生入学考试',
        status: 'info',
        tag: '必考',
        tagType: 'error',
        caption: '及格分数 60 分',
        path: '/pages/quiz/quiz'
      },
      {
        id: 3,
        title: '校园地图',
        subtitle: '熟悉校园环境',
        status: 'success',
        tag: '推荐',
        tagType: 'info',
        caption: '查看重点位置',
        path: '/pages/map/map'
      },
      {
        id: 4,
        title: '常见问题',
        subtitle: '入学答疑解惑',
        status: 'neutral',
        tag: '帮助',
        tagType: 'neutral',
        caption: '快速找到答案',
        path: '/pages/faq/faq'
      }
    ],
    milestones: [
      { id: 1, title: '收到录取通知', date: '2025-08-01' },
      { id: 2, title: '完成线上安全教育', date: '2025-08-10' },
      { id: 3, title: '到校报到', date: '2025-09-01' }
    ],
    skeletons: [1, 2, 3, 4]
  },

  onShow() {
    this.checkToken();
    this.updateTabBar(0);
    this.setData({ greeting: this.getGreeting() });
  },

  checkToken() {
    this.setData({
      tokenPresent: this.checkAuth()
    });
  },

  async handleHealthCheck() {
    if (this.data.healthStatus.loading) {
      return;
    }
    
    this.setData({
      'healthStatus.loading': true,
      'healthStatus.message': '正在检测...',
      'healthStatus.statusClass': ''
    });

    try {
      const res = await request({
        url: '/api/health',
        method: 'GET',
        showErrorToast: false
      });
      
      const timeStr = formatDate(new Date(), 'HH:mm');
      
      this.setData({
        'healthStatus.loading': false,
        'healthStatus.message': '系统运行正常',
        'healthStatus.statusClass': 'state-dot--success',
        'healthStatus.checkedAt': timeStr
      });
      
      this.showSuccess('系统正常');
    } catch (error) {
      const timeStr = formatDate(new Date(), 'HH:mm');
      
      this.setData({
        'healthStatus.loading': false,
        'healthStatus.message': '后端服务未启动',
        'healthStatus.statusClass': 'state-dot--error',
        'healthStatus.checkedAt': timeStr
      });
      
      this.showError('后端服务未启动');
    }
  },

  navigateToFeature(event) {
    const index = event.currentTarget.dataset.index;
    const feature = this.data.features[index];
    if (!feature || !feature.path) return;

    const { smartNavigate } = require('../../utils/navigation');

    if (feature.path === '/pages/quiz/quiz') {
      const auth = require('../../utils/auth');
      const token = auth.getToken && auth.getToken();
      if (!token) {
        wx.navigateTo({ url: '/pages/login/login' });
        return;
      }
      smartNavigate(feature.path);
      return;
    }

    smartNavigate(feature.path);
  },

  reloadFeatures() {
    // 功能列表重新加载（当前是静态数据）
    this.showSuccess('已刷新');
  }
});
